'use client'
import React, { useState } from 'react'
import { usePathname } from 'next/navigation'
import s from './index.module.css'
import { useEventEmitterContextContext } from '@/context/event-emitter'
import classNames from '@/utils/classnames'

type HeaderWrapperProps = {
  children: React.ReactNode
}

const HeaderWrapper = ({ children }: HeaderWrapperProps) => {
  const pathname = usePathname()
  const isBordered = [
    '/apps',
    '/datasets',
    '/datasets/create',
    '/tools'
  ].includes(pathname)
  // Check if the current path is a workflow canvas & fullscreen
  const inWorkflowCanvas = pathname.endsWith('/workflow')
  const workflowCanvasMaximize =
    localStorage.getItem('workflow-canvas-maximize') === 'true'
  const [hideHeader, setHideHeader] = useState(workflowCanvasMaximize)
  const { eventEmitter } = useEventEmitterContextContext()

  eventEmitter?.useSubscription((v: any) => {
    if (v?.type === 'workflow-canvas-maximize') setHideHeader(v.payload)
  })

  // 辅助函数，用于安全地获取布尔值
  const getBooleanFromStorage = (
    key: string,
    defaultValue: boolean = false
  ): boolean => {
    try {
      const value = localStorage.getItem(key)
      if (value === null) return defaultValue
      return JSON.parse(value)
    } catch {
      return defaultValue
    }
  }

  return (
    <div
      style={{
        display: !getBooleanFromStorage('isInternal_jump') ? 'none' : 'flex'
      }}
      className={classNames(
        'sticky left-0 right-0 top-0 z-[15] flex min-h-[56px] shrink-0 grow-0 basis-auto flex-col',
        s.header,
        isBordered ? 'border-b border-divider-regular' : '',
        hideHeader && inWorkflowCanvas && 'hidden'
      )}
    >
      {children}
    </div>
  )
}
export default HeaderWrapper
